package com.qaml.mes.device.application.task;

import com.qaml.mes.device.dao.CheckUpkeepMessageDO;
import com.qaml.mes.device.repository.CheckUpkeepMessageRepository;
import com.qaml.mes.device.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName CleanCheckUpkeepMessageTask
 * @Description 删除消息
 * @Author leikai
 * @Date 2024/3/12 0012 13:57
 * @Version 1.0
 */
@RefreshScope
@Component
@Slf4j
public class CleanCheckUpkeepMessageTask {


    @Resource
    private CheckUpkeepMessageRepository checkUpkeepMessageRepository;


    /**
     * 0 0 2 1 * ?   表示在每月的1日的凌晨2点调整任务
     */
    //@Scheduled(cron = "0 0 2 1 * ? ")
    public void cleanCheckUpkeepMessage() {
        log.info("开始清理消息");
        Date beforeDay = DateUtils.addDays(new Date(), -1);
        String yearMonth = DateUtils.format(beforeDay, "yyyy-MM");
        Date startDateByMonth = DateUtils.getStartDateByMonth(yearMonth);
        Date endDateByMonth = DateUtils.getEndDateByMonth(yearMonth);
        List<CheckUpkeepMessageDO> messageDOList = checkUpkeepMessageRepository.getNoDeletedMessage(startDateByMonth, endDateByMonth);
        if (CollectionUtils.isEmpty(messageDOList)) {
            log.info("没有需要清理的消息");
            return;
        }
        List<String> ids = messageDOList.stream().map(CheckUpkeepMessageDO::getId).collect(Collectors.toList());
        checkUpkeepMessageRepository.deleteAll(ids);
        log.info("结束清理消息");
    }
}